package com.fs.uc.api.inner.resource;

import com.fs.uc.api.inner.dto.*;
import com.fs.uc.base.Const;
import com.fs.uc.base.domain.Permission;
import com.fs.uc.base.domain.Person;
import com.fs.uc.base.domain.Role;
import com.fs.uc.base.exception.CustomException;
import com.fs.uc.api.inner.service.InnerService;
import com.fs.uc.core.SubjectType;
import com.fs.uc.core.permcheck.SubjectInfo;
import com.fs.uc.security.JwtUserInfo;
import com.fs.uc.security.JwtUtil;
import io.smallrye.jwt.auth.principal.ParseException;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 崔超
 * 2021/12/8
 */
@Path(Const.URL_PREFIX + "/inner")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Transactional
public class InnerResource {

    @Inject
    InnerService innerService;
    @Inject
    JwtUtil jwtUtil;

    /*
    基础信息服务：获取所有园区
     */
    @GET
    @Path("/all/park")
    public List<Park> allPark(){
        return innerService.getAllPark();
    }

    /*
    网关鉴权
     */
    @GET
    @Path("/gateway/check")
    public RespCheckAuth checkAuth(@QueryParam("token") String token, @QueryParam("method") String method,
                                   @QueryParam("resource") String resource) {
        RespCheckAuth.RespCheckAuthBuilder builder = RespCheckAuth.builder();
        try {
            JwtUserInfo userInfo = jwtUtil.getUserInfo(token);
            boolean hasPerm = innerService.checkPermission(userInfo.subjectType, userInfo.subjectId, method, resource);
            SubjectInfo subjectInfo = innerService.getSubjectInfo(userInfo.subjectType, userInfo.subjectId);
            return builder.tokenValid(true).hasPermission(hasPerm).info(subjectInfo).build();
        } catch (ParseException e) {
            return builder.tokenValid(false).hasPermission(false).build();
        }
    }

    /*
    基础信息服务获取用户当前所属企业（返回基础信息服务的企业id）
     */
    @GET
    @Path("/affiliation/{personId}")
    public PersonAffiliation affiliation(@PathParam("personId") Long personId) {
        Person person = innerService.getPerson(personId);
        if (person.currentOrg == null) {
            throw new CustomException("没有所属组织");
        }
        return new PersonAffiliation(person.id, person.currentOrg.remoteId);
    }

    /*
    获取个人用户的所有角色,网关使用
     */
    @Path("/roles/all")
    @GET
    public List<String> getRoleOfUsers(@NotNull @QueryParam("userId") Long personId) {
        Set<Role> roles = innerService.getRolesOfPerson(personId);
        return roles.stream().map(role -> role.name).collect(Collectors.toList());
    }

    /*
    创建企业管理员用户(企业org要同时创建)
     */
    @Path("/boss_user")
    @POST
    public RespUserInfo createBossUser(@Valid ReqCreateUser req) {
        Person person = innerService.createEnterpriseAndBoss(req.getTenantId(), req.getEnterpriseId(),
                req.getPhone(), req.getEnterpriseName(), req.getPersonName());
        return new RespUserInfo(person.id, person.name);
    }


    /*
    移交企业管理员角色
     */
    @Path("/enterprise/admin")
    @PUT
    public void setEnterpriseAdmin(@Valid ReqBossTransfer req) {
        innerService.transferEnterpriseBoss(req.getEnterpriseId(), req.getNewBossUserId());
    }

    /*
    查询租户下的模块开通状态
     */
    @Path("/modules")
    @GET
    public List<RespModule> getModules(@QueryParam("tenantId") Long tenantId) {
        return innerService.getAllModuleStateOfPark(tenantId);
    }

    @POST
    @Path("/find/persons")
    public List<RespPerson> findPersons(ReqFindPersons req) throws Exception {
        return innerService.getPersons(req.personIds);
    }

    //todo
    //给员工发送访客到访消息
    @Path("/message/visit_come")
    @POST
    public void sendVisitorComeMessage(@Valid ReqSendVisitorComeMsg req) {

    }

    //todo
    //给访客发送员工是否同意访问的消息
    @Path("/message/visit_auth")
    @POST
    public void sendVisitorAuthorizeMessage(@Valid ReqSendVisitorAuthMsg req) {
    }

    //todo
    //给员工发送邀请成功消息
    @POST
    @Path("/message/invite_result")
    public void send(@Valid ReqSendInvitationResult req) {

    }

    //纯粹用来单元测试
    @GET
    @Path("/test/user/perm")
    public List<TestPermission> testUserPerm(@QueryParam("personId") Long personId){
        return innerService.testUserPermission(personId);
    }

    //纯粹用来单元测试
    @GET
    @Path("/test/user/sub")
    public SubjectInfo testUserSubject(@QueryParam("personId") Long personId){
        return innerService.testUserSubjectInfo(personId);
    }
}
